<?php

class WxMenuAction extends CommonAction
{
	public function index(){
		$model = M();
		if(isset($_REQUEST['pid']))
			$parent_id = intval($_REQUEST['pid']);
		else
			$parent_id = intval($_SESSION['menu_pid']);
		
		$_SESSION['menu_pid'] = $parent_id;
		
		$map['pid'] = $parent_id;
		$model = D("WxMenu");
		if (! empty ( $model ))
		{
			$this->assign("pid",$parent_id);
			if($parent_id > 0)
			{
				$pp_id = $model->where('id = '.$parent_id)->getField('pid');
				$this->assign("pp_id",$pp_id);
			}
			
			$count = $model->where('pid = '.$parent_id)->count('id');
			
			$sql = 'SELECT gc.*,COUNT(gc1.id) AS child 
					FROM '.C("DB_PREFIX").'wx_menu as gc 
					LEFT JOIN '.C("DB_PREFIX").'wx_menu as gc1 ON gc1.pid = gc.id 
					WHERE gc.pid = '.$parent_id.' GROUP BY gc.id';
			$this->_sqlList($model,$sql,$count,$map);
			
		}
		/*
		$sql = 'SELECT COUNT(DISTINCT id) AS tcount FROM '.C("DB_PREFIX").'wx_menu ';
		
		$count = $model->query($sql);
		$count = $count[0]['tcount'];

		$sql = 'SELECT * FROM '.C("DB_PREFIX").'wx_menu ';
			
		$this->_sqlList($model,$sql,$count,$parameter,'id');
		*/
		
		$this->display ();
		return;
	}
	public function add(){
		$model = D ('WxPic');
		$list = $model->where('status=1 and ptype=1')->order('sort,create_time desc')->limit('30')->select();
		$new_list = D('WxNew')->where('status=1')->order('create_time desc,id desc')->limit('10')->select();
		foreach($new_list as $k=>$v){
			$id = $v['id'];
			$item_list = D('WxNewItem')->where('status=1 and pid='.$id)->order('sort,id')->select();
			$new_list[$k]['item'] = $item_list;			
		}
		
		$this->assign('list',$list);
		$this->assign('new_list',$new_list);

		$cate_list = D("WxMenu")->where('status = 1 AND pid = 0')->field('id,pid,title')->order('sort ASC,id ASC')->findAll();
		$this->assign("cate_list",$cate_list);
		$this->display();
	}
	public function insert()
	{
		$model = D("WxMenu");
		if(false === $data = $model->create())
		{
			$this->error($model->getError());
		}
		$data['create_time'] = time();
		//保存当前数据对象
		$list=$model->add($data);
		if ($list !== false)
		{
			$this->saveLog(1,$list);
			$this->success (L('ADD_SUCCESS'));
		}
		else
		{
			$this->saveLog(0,$list);
			$this->error (L('ADD_ERROR'));
		}
	}
	public function edit(){
		$id = intval($_REQUEST['id']);
		$vo = D("WxMenu")->getById($id);
		$this->assign ( 'vo', $vo );
		$model = D ('WxPic');
		$list = $model->where('status=1 and ptype=1')->order('sort,create_time desc')->limit('30')->select();
		$new_list = D('WxNew')->where('status=1')->order('create_time desc,id desc')->limit('10')->select();
		foreach($new_list as $k=>$v){
			$id = $v['id'];
			$item_list = D('WxNewItem')->where('status=1 and pid='.$id)->order('sort,id')->select();
			$new_list[$k]['item'] = $item_list;			
		}
		$key_item = '';
		if($vo['gtype']==4){
			$key_item = D('WxNewItem')->where('pid='.$vo['medianew_id'])->order('sort,id')->select();
		}
		
		$this->assign('list',$list);
		$this->assign('new_list',$new_list);
		$this->assign('key_item',$key_item);
		
		$childs = D("WxMenu")->where('pid='.$id)->select();
		$childs[] = $id;
		$cate_list = D("WxMenu")->where('status = 1 AND pid = 0 AND id not in ('.implode(',', $childs).')')->field('id,pid,title')->order('sort ASC,id ASC')->findAll();
		//$cate_list = D("WxMenu")->toFormatTree($cate_list,array('title'),'id');
		//echo "<pre>"; var_dump($cate_list); exit;
		$this->assign("cate_list",$cate_list);
		$this->display();
	}
	
	public function update()
	{
		$id = intval($_REQUEST['id']);
		$name=$this->getActionName();
		$model = D ($name);
		if (false === $data = $model->create ()) {
			$this->error ( $model->getError () );
		}
		
		$list=$model->save($data);
		
		if (false !== $list)
		{
			//$this->saveLog(1,$id);
			$this->assign('jumpUrl', Cookie::get ( '_currentUrl_' ) );
			$this->success (L('EDIT_SUCCESS'));
		}
		else
		{
			//错误提示
			//$this->saveLog(0,$id);
			$this->error (L('EDIT_ERROR'));
		}
	}
	
	public function remove()
	{
		//删除指定记录
		$result = array('isErr'=>0,'content'=>'');
		$id = $_REQUEST['id'];

		if(!empty($id))
		{
			$name=$this->getActionName();
			$model = D($name);
			$pk = $model->getPk ();
			
			
			$condition = array ($pk => array ('in', explode ( ',', $id ) ) );
			$datas = $model->where($condition )->field('best_img')->findAll();
			if(false !== $model->where ( $condition )->delete ())
			{
				foreach($datas as $data)
				{
					if(!empty($data['best_img']))
						@unlink(RES_ROOT.$data['best_img']);
				}
				$this->saveLog(1,$id);
			}
			else
			{
				$this->saveLog(0,$id);
				$result['isErr'] = 1;
				$result['content'] = L('REMOVE_ERROR');
			}
		}
		else
		{
			$result['isErr'] = 1;
			$result['content'] = L('ACCESS_DENIED');
		}
		
		die(json_encode($result));
	}
	
	public function updatemenu(){
		$name=$this->getActionName();
		$model = D($name);
		$token = get_token();
		$list = $model->where('status=1 and pid=0')->order('sort,id desc')->select();
		
		$data = '{"button": [';
		$c = count($list);
		foreach($list as $k=>$v){
			
			$c_list = $model->where('status=1 and pid='.$v['id'])->order('sort,id desc')->select();
			if(count($c_list)>0){
				$data .= ' {"name":"'.$v['title'].'","sub_button":[';
				foreach($c_list as $key=>$val){
					if($val['gtype']==1){
						$data .= '{"type": "view", 
						"name": "'.$val['title'].'", 
						"url": "'.$val['url'].'"},';
					}else{
						$data .= '{"type": "click", 
						"name": "'.$val['title'].'", 
						"key": "V1001_G'.$val['id'].'"},';
					}
				}
				$data = substr($data,0,-1);	
				
				if($k==($c-1)){
					$data .= ']}';		
				}else{
					$data .= ']},';	
				}
							
			}else{
				if($v['gtype']==1){
					$data .= '{"type": "view", 
					"name": "'.$v['title'].'", 
					"url": "'.$v['url'].'"},';
				}else{
					$data .= '{"type": "click", 
					"name": "'.$v['title'].'", 
					"key": "V1001_G'.$v['id'].'"},';
				}
				$j = $k+1;
				if($j==count($list)){
					$data = substr($data,0,-1);
				}
				
			}
			
		}
		$data .= '}]}';
		
		/*
		$data = '{
			 "button": [
						{
							"type": "view", 
							"name": "精选内容", 
							"url": "'.$url.'"
						}], 
						"button": [
						{
							"type": "view", 
							"name": "征集", 
							"url": "'.$mu.'"
						}],
						"button": [
						{
							"type": "click", 
							"name": "猫宁", 
							"key": "V1001_GOOD"
						}
					]
		}';
		*/
		
		echo createMenu($token,$data); 
		exit;
		$this->redirect('WxMenu/index');
	}
}
 
 
function get_token() {  
	$appid = 'wxbcb9db2f64155de8';
	$secret = '64dc86abe049f26e0656158c39d8eb4e';
	
	$data = D("Token")->find();
	if(count($data)>0){
		$token = $data['tk'];
		$ctime = $data['create_time'];	
		if ($ctime<time()) {
			$token_url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$secret;
			$access_token = json_decode(file_get_contents($token_url));
			if (isset($access_token->errcode)) {
				echo '<h1>错误：</h1>'.$access_token->errcode;
				echo '<br/><h2>错误信息：</h2>'.$access_token->errmsg;
				exit;
			}
			$token = $access_token->access_token;
			$time = time()+3600;
			$tsql = "update tbl_token set tk='".$token."',create_time=".$time;
			D("Token")->query($tsql);
			
		}
	}else{
		$token_url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$secret;
		$access_token = json_decode(file_get_contents($token_url));
		if (isset($access_token->errcode)) {
			echo '<h1>错误：</h1>'.$access_token->errcode;
			echo '<br/><h2>错误信息：</h2>'.$access_token->errmsg;
			exit;
		}
		$token = $access_token->access_token;
		$time = time()+3600;
		$tsql = "insert into tbl_token (tk,create_time) values('".$token."',".$time.")";
		D("Token")->query($tsql);
	}
	
  return $token;  
}

function createMenu($token,$data){
	$url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=".$token;
	$params = array('http' => array(
                 'method' => 'POST',
                 'content' => $data
              ));
    if ($optional_headers !== null) {
       $params['http']['header'] = $optional_headers;
    }
    $ctx = stream_context_create($params);
    $fp = @fopen($url, 'rb', false, $ctx);
    if (!$fp) {
       throw new Exception("Problem with $url, $php_errormsg");
    }
    $response = @stream_get_contents($fp);
    if ($response === false) {
       throw new Exception("Problem reading data from $url, $php_errormsg");
    }
    return $response;
	/*
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=".$token);
	curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
	curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
	curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	$tmpInfo = curl_exec($ch);
	if (curl_errno($ch)) {
	  return curl_error($ch);
	}

	curl_close($ch);
	return $tmpInfo;
	*/
}
function getChildLink($child,$id)
{
	if($child > 0)
		return '<a href="'.U('WxMenu/index',array('pid'=>$id)).'">'.L('SHOW_CHILD').'</a>';
	else
		return '';
}

?>